package com.davidtorma.site;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;

public class GalleryImageServiceImpl implements GalleryImageService {
	private List<GalleryItem> galleryItems = new ArrayList<GalleryItem>();

	public GalleryImageServiceImpl() {
		initGalleryItems();
	}

	public List<GalleryItem> getGalleryItems() {
		return galleryItems;
	}

	private void initGalleryItems() {
		File iconRoot = new File("e:\\git\\davidtorma-web\\davidtorma.web\\src\\main\\webapp\\" + Constants.ICON_PATH);
		File[] mainCategory = iconRoot.listFiles(directoryFilter);
		if (mainCategory != null) {
			for (File main : mainCategory) {
				File[] subCategory = main.listFiles(directoryFilter);
				if (subCategory.length == 0) {
					addItems(main);
				} else {
					for (File sub : subCategory) {
						addSubItems(sub);
					}
				}
			}
		}
	}

	private static FileFilter directoryFilter = new FileFilter() {
		public boolean accept(File file) {
			return file.isDirectory();
		}
	};

	private void addSubItems(File dir) {
		String[] images = dir.list();
		for (String img : images) {
			GalleryItem item = new GalleryItem();
			item.setMainCategory(dir.getParentFile().getName());
			item.setSubCategory(dir.getName());
			galleryItems.add(item);
		}
	}

	private void addItems(File dir) {
		String[] images = dir.list();
		for (String img : images) {
			GalleryItem item = new GalleryItem();
			item.setMainCategory(dir.getName());
			item.setImageName(img);
			galleryItems.add(item);
		}
	}
}
